package tr.edu.metu.is.mega.client.course.student;

import java.util.ArrayList;
import java.util.List;

import tr.edu.metu.is.mega.client.core.AuthUtils;
import tr.edu.metu.is.mega.client.core.MegaUtil;
import tr.edu.metu.is.mega.client.core.QueryCallback;
import tr.edu.metu.is.mega.client.core.event.SelectionEventBus;
import tr.edu.metu.is.mega.client.core.event.SelectionEventListener;
import tr.edu.metu.is.mega.client.course.CourseChangeEvent;
import tr.edu.metu.is.mega.client.resource.MEGAResourceBundle;
import tr.edu.metu.is.mega.client.resource.MEGAResources;
import tr.edu.metu.is.mega.client.resource.MegaConstants;
import tr.edu.metu.is.mega.client.service.GwtCourseService;
import tr.edu.metu.is.mega.client.service.GwtCourseServiceAsync;
import tr.edu.metu.is.mega.client.widgets.MegaTextField;
import tr.edu.metu.is.mega.common.dto.CourseDTO;
import tr.edu.metu.is.mega.common.dto.CourseStudentDTO;
import tr.edu.metu.is.mega.common.dto.TeamDTO;
import tr.edu.metu.is.mega.common.dto.UserDTO;

import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FillLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Image;

/**
 * Window for defining and changing lecture note records.
 */
public class TeamInformationPanel extends LayoutContainer {

    private MEGAResourceBundle resourceBundle;

    private Grid<BeanModel> grid;

    private BeanModelFactory beanModelFactory;

    private CourseDTO course;

    private Image teamPhoto;

    private MegaTextField teamNameField;

    /**
     * Default constructor.
     */
    public TeamInformationPanel() {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onRender(Element parent, int index) {
        super.onRender(parent, index);
        setLayout(new FillLayout());
        resourceBundle = MEGAResources.RESOURCEBUNDLE;
        beanModelFactory = BeanModelLookup.get().getFactory(UserDTO.class);

        FieldSet set = new FieldSet();
        set.setHeight(300);
        set.setLayout(new FillLayout());
        set.setHeading("Team Information");

        ContentPanel panel = new ContentPanel();
        panel.setBodyBorder(false);
        panel.setHeaderVisible(false);
        panel.setLayout(new ColumnLayout());

        LayoutContainer leftContainer = new LayoutContainer();

        teamPhoto = new Image();
        teamPhoto.setUrl(MegaConstants.EMPTY_TEAM_LOGO_PATH);
        teamPhoto.setWidth("150px");

        leftContainer.add(teamPhoto);

        LayoutContainer rightContainer = new LayoutContainer();

        LayoutContainer rightTopContainer = new LayoutContainer(new FormLayout());
        teamNameField = new MegaTextField("");
        teamNameField.setReadOnly(true);
        teamNameField.setFieldLabel("Team Name");
        rightTopContainer.add(teamNameField, new FormData("100%"));

        rightContainer.add(rightTopContainer);
        FieldSet membersSet = new FieldSet();
        membersSet.setHeight(200);
        membersSet.setLayout(new FillLayout());
        membersSet.setHeading("Members");
        membersSet.add(getGrid());
        rightContainer.add(membersSet);

        panel.add(leftContainer, new ColumnData(0.4));
        panel.add(rightContainer, new ColumnData(0.6));

        set.add(panel);
        add(set);
        SelectionEventBus.getInstance().registerListener(CourseChangeEvent.Update.class, new SelectionEventListener<CourseDTO>() {

            @Override
            public void selectionChanged(CourseDTO selectedObject) {
                course = selectedObject;
                AuthUtils.getInstance().getCurrentUser(new QueryCallback<UserDTO>() {

                    @Override
                    public void onQueryResult(UserDTO result) {
                        TeamDTO team = null;
                        for (TeamDTO teamDto : course.getTeams()) {
                            for (CourseStudentDTO studentDTO : teamDto.getMembers()) {
                                if (studentDTO.getUser().getPkid() == result.getPkid()) {
                                    team = teamDto;
                                    SelectionEventBus.getInstance().fireEvent(CourseChangeEvent.TEAMSELECTED, team);
                                    break;
                                }
                            }
                        }
                        if (team != null) {
                            grid.getStore().removeAll();
                            for (CourseStudentDTO studentDTO : team.getMembers()) {
                                grid.getStore().add(beanModelFactory.createModel(studentDTO.getUser()));
                            }
                            teamNameField.setValue(team.getTeamName());
                            if (team.getLogo() != null) {
                                teamPhoto.setUrl(MegaConstants.TEAM_PATH + team.getPkid() + "/" + team.getLogo());
                                teamPhoto.setWidth("150px");
                            }

                        }
                    }
                });

            }
        });
    }

    /**
     * Returns activity grid.
     * 
     * @return grid
     */
    private Grid<BeanModel> getGrid() {
        if (grid == null) {

            ListStore<BeanModel> store = new ListStore<BeanModel>();

            List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
            columns.add(new ColumnConfig(UserDTO.FIELD_FULL_NAME, resourceBundle.teamManagementTeamMembers(), 100));

            ColumnModel cm = new ColumnModel(columns);

            grid = new Grid<BeanModel>(store, cm);
            grid.setAutoExpandColumn(UserDTO.FIELD_FULL_NAME);

            MegaUtil.decoradeGridViewWithAutoHeight(grid, true);

        }
        return grid;
    }

    public static GwtCourseServiceAsync getService() {
        return GwtCourseService.Util.getInstance();
    }

}
